// ReaderSelfServicePanel.java - 完整的读者自助服务面板
package com.library.gui;

import com.library.entity.*;
import com.library.service.ReaderSelfService;
import com.library.service.LibraryDataService;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;

public class ReaderSelfServicePanel extends JPanel {
    private ReaderUser currentUser;
    private ReaderSelfService selfService;
    private LibraryDataService dataService;
    private JTabbedPane tabbedPane;

    // 各面板组件
    private JTable borrowTable;
    private DefaultTableModel borrowTableModel;
    private JTable bookSearchTable;
    private DefaultTableModel bookSearchTableModel;
    private JTable fineTable;
    private DefaultTableModel fineTableModel;
    private JTable reservationTable;
    private DefaultTableModel reservationTableModel;

    public ReaderSelfServicePanel(ReaderUser user, LibraryDataService dataService, ReaderSelfService selfService) {
        this.currentUser = user;
        this.dataService = dataService;
        this.selfService = selfService;
        initializeUI();
    }

    private void initializeUI() {
        setLayout(new BorderLayout());
        setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 创建顶部信息面板
        JPanel infoPanel = createInfoPanel();
        add(infoPanel, BorderLayout.NORTH);

        // 创建主选项卡面板
        tabbedPane = new JTabbedPane();
        tabbedPane.addTab("我的借阅", createBorrowPanel());
        tabbedPane.addTab("图书检索", createBookSearchPanel());
        tabbedPane.addTab("图书预约", createReservationPanel());
        tabbedPane.addTab("我的罚金", createFinePanel());
        tabbedPane.addTab("阅读统计", createStatisticsPanel());

        add(tabbedPane, BorderLayout.CENTER);
    }

    private JPanel createInfoPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(200, 200, 200)),
                BorderFactory.createEmptyBorder(10, 15, 10, 15)
        ));
        panel.setBackground(new Color(240, 245, 255));

        // 左侧欢迎信息
        JLabel welcomeLabel = new JLabel("欢迎使用自助服务系统，" + currentUser.getReader().getName() + "！");
        welcomeLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        welcomeLabel.setForeground(new Color(0, 102, 204));

        // 右侧统计信息
        JPanel statsPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 15, 0));
        statsPanel.setBackground(new Color(240, 245, 255));

        Map<String, Object> stats = selfService.getReaderStatistics(currentUser.getReader().getReaderId());

        statsPanel.add(createStatLabel("当前借阅", stats.get("currentBorrows") + " 本"));
        statsPanel.add(createStatLabel("超期图书", stats.get("overdueBorrows") + " 本"));
        statsPanel.add(createStatLabel("未缴罚金", String.format("%.2f 元", stats.get("totalFines"))));
        statsPanel.add(createStatLabel("有效预约", stats.get("activeReservations") + " 个"));

        panel.add(welcomeLabel, BorderLayout.WEST);
        panel.add(statsPanel, BorderLayout.EAST);

        return panel;
    }

    private JLabel createStatLabel(String title, String value) {
        JLabel label = new JLabel("<html><center><b>" + title + "</b><br>" + value + "</center></html>");
        label.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        label.setForeground(Color.DARK_GRAY);
        label.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10));
        return label;
    }

    private JPanel createBorrowPanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));

        // 表格列定义
        String[] columns = {"记录ID", "图书名称", "作者", "借阅日期", "应还日期", "状态", "续借次数", "操作"};
        borrowTableModel = new DefaultTableModel(columns, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return column == 7; // 只有操作列可编辑
            }
        };
        borrowTable = new JTable(borrowTableModel);
        borrowTable.setRowHeight(30);

        // 加载借阅数据
        loadBorrowData();

        JScrollPane scrollPane = new JScrollPane(borrowTable);
        panel.add(scrollPane, BorderLayout.CENTER);

        // 操作按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout());
        JButton refreshButton = new JButton("刷新列表");
        JButton renewButton = new JButton("续借选中图书");

        refreshButton.addActionListener(e -> loadBorrowData());
        renewButton.addActionListener(e -> renewSelectedBook());

        buttonPanel.add(refreshButton);
        buttonPanel.add(renewButton);
        panel.add(buttonPanel, BorderLayout.SOUTH);

        return panel;
    }

    private JPanel createBookSearchPanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));

        // 搜索面板
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JTextField searchField = new JTextField(25);
        JComboBox<String> searchType = new JComboBox<>(new String[]{"书名", "作者", "ISBN", "出版社"});
        JButton searchButton = new JButton("搜索");
        JButton showAllButton = new JButton("显示所有可借图书");

        searchPanel.add(new JLabel("搜索:"));
        searchPanel.add(searchType);
        searchPanel.add(searchField);
        searchPanel.add(searchButton);
        searchPanel.add(showAllButton);

        // 图书表格
        String[] columns = {"ISBN", "书名", "作者", "出版社", "出版日期", "可借复本", "馆藏位置", "操作"};
        bookSearchTableModel = new DefaultTableModel(columns, 0);
        bookSearchTable = new JTable(bookSearchTableModel);
        bookSearchTable.setRowHeight(30);

        // 加载初始数据（热门图书）
        loadPopularBooks();

        JScrollPane scrollPane = new JScrollPane(bookSearchTable);
        panel.add(searchPanel, BorderLayout.NORTH);
        panel.add(scrollPane, BorderLayout.CENTER);

        // 事件监听
        searchButton.addActionListener(e -> {
            String keyword = searchField.getText().trim();
            if (!keyword.isEmpty()) {
                searchBooks(keyword);
            }
        });

        showAllButton.addActionListener(e -> loadAllAvailableBooks());

        return panel;
    }

    private JPanel createReservationPanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));

        // 表格列定义
        String[] columns = {"预约ID", "图书名称", "预约日期", "保留至", "状态", "操作"};
        reservationTableModel = new DefaultTableModel(columns, 0);
        reservationTable = new JTable(reservationTableModel);
        reservationTable.setRowHeight(30);

        // 加载预约数据
        loadReservationData();

        JScrollPane scrollPane = new JScrollPane(reservationTable);
        panel.add(scrollPane, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout());
        JButton refreshButton = new JButton("刷新");
        JButton newReservationButton = new JButton("新建预约");
        JButton cancelButton = new JButton("取消选中预约");

        refreshButton.addActionListener(e -> loadReservationData());
        newReservationButton.addActionListener(e -> showNewReservationDialog());
        cancelButton.addActionListener(e -> cancelSelectedReservation());

        buttonPanel.add(refreshButton);
        buttonPanel.add(newReservationButton);
        buttonPanel.add(cancelButton);
        panel.add(buttonPanel, BorderLayout.SOUTH);

        return panel;
    }

    private JPanel createFinePanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));

        // 罚金汇总信息
        JPanel summaryPanel = new JPanel(new GridLayout(1, 3, 10, 10));
        summaryPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        double totalFines = selfService.getTotalUnpaidFines(currentUser.getReader().getReaderId());
        List<Fine> fines = selfService.getReaderFines(currentUser.getReader().getReaderId());
        long unpaidCount = 0;
        for (Fine fine : fines) {
            if (fine.getStatus() == Fine.FineStatus.UNPAID) {
                unpaidCount++;
            }
        }

        summaryPanel.add(createSummaryCard("总欠款", String.format("%.2f 元", totalFines), Color.RED));
        summaryPanel.add(createSummaryCard("未缴记录", unpaidCount + " 条", Color.ORANGE));
        summaryPanel.add(createSummaryCard("最后更新", java.time.LocalDate.now().toString(), Color.BLUE));

        // 罚金明细表格
        String[] columns = {"罚金ID", "事由", "金额", "产生日期", "状态", "操作"};
        fineTableModel = new DefaultTableModel(columns, 0);
        fineTable = new JTable(fineTableModel);
        fineTable.setRowHeight(30);

        loadFineData();

        JScrollPane scrollPane = new JScrollPane(fineTable);

        // 操作按钮
        JPanel buttonPanel = new JPanel(new FlowLayout());
        JButton refreshButton = new JButton("刷新");
        JButton payButton = new JButton("缴纳选中罚金");

        refreshButton.addActionListener(e -> loadFineData());
        payButton.addActionListener(e -> paySelectedFine());

        buttonPanel.add(refreshButton);
        buttonPanel.add(payButton);

        panel.add(summaryPanel, BorderLayout.NORTH);
        panel.add(scrollPane, BorderLayout.CENTER);
        panel.add(buttonPanel, BorderLayout.SOUTH);

        return panel;
    }

    private JPanel createStatisticsPanel() {
        JPanel panel = new JPanel(new GridLayout(2, 2, 15, 15));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        Map<String, Object> stats = selfService.getReaderStatistics(currentUser.getReader().getReaderId());
        List<BorrowRecord> records = selfService.getReaderBorrowRecords(currentUser.getReader().getReaderId());

        // 计算阅读偏好
        Map<String, Long> categoryCount = new HashMap<>();
        for (BorrowRecord record : records) {
            Book book = dataService.findBookByIsbn(record.getBookIsbn());
            if (book != null) {
                String category = book.getCategory();
                categoryCount.put(category, categoryCount.getOrDefault(category, 0L) + 1);
            }
        }

        String favoriteCategory = "暂无数据";
        long maxCount = 0;
        for (Map.Entry<String, Long> entry : categoryCount.entrySet()) {
            if (entry.getValue() > maxCount) {
                maxCount = entry.getValue();
                favoriteCategory = entry.getKey();
            }
        }

        panel.add(createStatCard("阅读统计",
                "总借阅量: " + records.size() + " 本",
                "本月借阅: " + getCurrentMonthBorrows(records) + " 本"));

        panel.add(createStatCard("借阅状态",
                "当前借阅: " + stats.get("currentBorrows") + " 本",
                "超期图书: " + stats.get("overdueBorrows") + " 本"));

        panel.add(createStatCard("阅读偏好",
                "最常阅读: " + favoriteCategory,
                "阅读广度: " + categoryCount.size() + " 个分类"));

        panel.add(createStatCard("账户状态",
                "信用积分: 95",
                "会员等级: 黄金读者"));

        return panel;
    }

    private long getCurrentMonthBorrows(List<BorrowRecord> records) {
        long count = 0;
        java.time.LocalDate now = java.time.LocalDate.now();
        for (BorrowRecord record : records) {
            if (record.getBorrowDate().getMonth() == now.getMonth() &&
                    record.getBorrowDate().getYear() == now.getYear()) {
                count++;
            }
        }
        return count;
    }

    private JPanel createSummaryCard(String title, String value, Color color) {
        JPanel card = new JPanel(new BorderLayout());
        card.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(color),
                BorderFactory.createEmptyBorder(10, 10, 10, 10)
        ));
        card.setBackground(Color.WHITE);

        JLabel titleLabel = new JLabel(title, JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
        titleLabel.setForeground(color);

        JLabel valueLabel = new JLabel(value, JLabel.CENTER);
        valueLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));

        card.add(titleLabel, BorderLayout.NORTH);
        card.add(valueLabel, BorderLayout.CENTER);

        return card;
    }

    private JPanel createStatCard(String title, String line1, String line2) {
        JPanel card = new JPanel(new BorderLayout());
        card.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(Color.GRAY),
                BorderFactory.createEmptyBorder(15, 15, 15, 15)
        ));
        card.setBackground(Color.WHITE);

        JLabel titleLabel = new JLabel(title, JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        titleLabel.setForeground(new Color(0, 102, 204));

        JPanel contentPanel = new JPanel(new GridLayout(2, 1, 5, 5));
        contentPanel.setBackground(Color.WHITE);
        contentPanel.add(new JLabel(line1));
        contentPanel.add(new JLabel(line2));

        card.add(titleLabel, BorderLayout.NORTH);
        card.add(contentPanel, BorderLayout.CENTER);

        return card;
    }

    // 数据加载方法
    private void loadBorrowData() {
        borrowTableModel.setRowCount(0);
        List<BorrowRecord> records = selfService.getReaderBorrowRecords(currentUser.getReader().getReaderId());

        for (BorrowRecord record : records) {
            Book book = dataService.findBookByIsbn(record.getBookIsbn());
            String status = record.isOverdue() ? "超期" :
                    record.getStatus() == BorrowRecord.BorrowStatus.BORROWED ? "借阅中" : "已归还";

            borrowTableModel.addRow(new Object[]{
                    record.getRecordId(),
                    book != null ? book.getTitle() : "未知图书",
                    book != null ? book.getAuthor() : "未知作者",
                    record.getBorrowDate(),
                    record.getDueDate(),
                    status,
                    record.getRenewCount(),
                    "操作"
            });
        }
    }

    private void loadPopularBooks() {
        bookSearchTableModel.setRowCount(0);
        List<Book> popularBooks = selfService.getPopularBooks();

        for (Book book : popularBooks) {
            bookSearchTableModel.addRow(new Object[]{
                    book.getIsbn(),
                    book.getTitle(),
                    book.getAuthor(),
                    book.getPublisher(),
                    book.getPublishDate(),
                    book.getAvailableCopies(),
                    book.getLocation(),
                    book.getAvailableCopies() > 0 ? "借阅" : "预约"
            });
        }
    }

    private void loadAllAvailableBooks() {
        bookSearchTableModel.setRowCount(0);
        List<Book> allBooks = dataService.getAllBooks();
        List<Book> availableBooks = new ArrayList<>();

        for (Book book : allBooks) {
            if (book.getAvailableCopies() > 0) {
                availableBooks.add(book);
            }
        }

        for (Book book : availableBooks) {
            bookSearchTableModel.addRow(new Object[]{
                    book.getIsbn(),
                    book.getTitle(),
                    book.getAuthor(),
                    book.getPublisher(),
                    book.getPublishDate(),
                    book.getAvailableCopies(),
                    book.getLocation(),
                    "借阅"
            });
        }
    }

    private void searchBooks(String keyword) {
        bookSearchTableModel.setRowCount(0);
        List<Book> books = selfService.searchAvailableBooks(keyword);

        for (Book book : books) {
            bookSearchTableModel.addRow(new Object[]{
                    book.getIsbn(),
                    book.getTitle(),
                    book.getAuthor(),
                    book.getPublisher(),
                    book.getPublishDate(),
                    book.getAvailableCopies(),
                    book.getLocation(),
                    book.getAvailableCopies() > 0 ? "借阅" : "预约"
            });
        }
    }

    private void loadReservationData() {
        reservationTableModel.setRowCount(0);
        List<Reservation> reservations = selfService.getReaderReservations(currentUser.getReader().getReaderId());

        for (Reservation reservation : reservations) {
            Book book = dataService.findBookByIsbn(reservation.getBookIsbn());
            String status = reservation.isExpired() ? "已过期" :
                    reservation.getStatus() == Reservation.ReservationStatus.ACTIVE ? "有效" : "已取消";

            reservationTableModel.addRow(new Object[]{
                    reservation.getReservationId(),
                    book != null ? book.getTitle() : "未知图书",
                    reservation.getReserveDate(),
                    reservation.getExpireDate(),
                    status,
                    "操作"
            });
        }
    }

    private void loadFineData() {
        fineTableModel.setRowCount(0);
        List<Fine> fines = selfService.getReaderFines(currentUser.getReader().getReaderId());

        for (Fine fine : fines) {
            String status = fine.getStatus() == Fine.FineStatus.UNPAID ? "未缴纳" : "已缴纳";

            fineTableModel.addRow(new Object[]{
                    fine.getFineId(),
                    fine.getReason(),
                    String.format("%.2f 元", fine.getAmount()),
                    fine.getCreateDate(),
                    status,
                    "操作"
            });
        }
    }

    // 操作方法
    private void renewSelectedBook() {
        int selectedRow = borrowTable.getSelectedRow();
        if (selectedRow < 0) {
            JOptionPane.showMessageDialog(this, "请选择要续借的图书!");
            return;
        }

        String recordId = (String) borrowTableModel.getValueAt(selectedRow, 0);
        boolean success = selfService.renewBook(recordId, currentUser.getReader().getReaderId());

        if (success) {
            JOptionPane.showMessageDialog(this, "续借成功!");
            loadBorrowData();
        } else {
            JOptionPane.showMessageDialog(this, "续借失败，可能已达到最大续借次数或图书已超期!");
        }
    }

    private void cancelSelectedReservation() {
        int selectedRow = reservationTable.getSelectedRow();
        if (selectedRow < 0) {
            JOptionPane.showMessageDialog(this, "请选择要取消的预约!");
            return;
        }

        String reservationId = (String) reservationTableModel.getValueAt(selectedRow, 0);
        boolean success = selfService.cancelReservation(reservationId, currentUser.getReader().getReaderId());

        if (success) {
            JOptionPane.showMessageDialog(this, "预约取消成功!");
            loadReservationData();
        } else {
            JOptionPane.showMessageDialog(this, "取消失败!");
        }
    }

    private void paySelectedFine() {
        int selectedRow = fineTable.getSelectedRow();
        if (selectedRow < 0) {
            JOptionPane.showMessageDialog(this, "请选择要缴纳的罚金!");
            return;
        }

        String fineId = (String) fineTableModel.getValueAt(selectedRow, 0);
        boolean success = selfService.payFine(fineId, currentUser.getReader().getReaderId());

        if (success) {
            JOptionPane.showMessageDialog(this, "罚金缴纳成功!");
            loadFineData();
        } else {
            JOptionPane.showMessageDialog(this, "缴纳失败!");
        }
    }

    private void showNewReservationDialog() {
        JDialog dialog = new JDialog((Frame) SwingUtilities.getWindowAncestor(this), "新建图书预约", true);
        dialog.setSize(400, 200);
        dialog.setLocationRelativeTo(this);

        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        JLabel instructionLabel = new JLabel("<html><center>请输入要预约图书的ISBN号：</center></html>");
        JTextField isbnField = new JTextField();
        JButton searchButton = new JButton("搜索并预约");
        JButton cancelButton = new JButton("取消");

        searchButton.addActionListener(e -> {
            String isbn = isbnField.getText().trim();
            if (isbn.isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "请输入ISBN号!");
                return;
            }

            Book book = dataService.findBookByIsbn(isbn);
            if (book == null) {
                JOptionPane.showMessageDialog(dialog, "未找到该ISBN对应的图书!");
                return;
            }

            if (book.getAvailableCopies() > 0) {
                JOptionPane.showMessageDialog(dialog, "该图书目前有可借复本，无需预约!");
                return;
            }

            boolean success = selfService.reserveBook(currentUser.getReader().getReaderId(), isbn);
            if (success) {
                JOptionPane.showMessageDialog(dialog, "预约成功!");
                dialog.dispose();
                loadReservationData();
            } else {
                JOptionPane.showMessageDialog(dialog, "预约失败，请检查您的预约权限或重试!");
            }
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        JPanel buttonPanel = new JPanel(new FlowLayout());
        buttonPanel.add(searchButton);
        buttonPanel.add(cancelButton);

        panel.add(instructionLabel, BorderLayout.NORTH);
        panel.add(isbnField, BorderLayout.CENTER);
        panel.add(buttonPanel, BorderLayout.SOUTH);

        dialog.add(panel);
        dialog.setVisible(true);
    }
}
